import { orderDetail, showPrice, completeOrder, backOrder } from "@/api/index";
import { router, showToast, showConfirmDialog } from "@/util/index";
import { userStore } from "@/store/index";
interface ICategory {
  id: number;
  name: string;
  unit: string;
  unitPrice: number;
}
interface IOutboundItem {
  key: number;
  categoryId: number | null;
  name: string;
  unit: string;
  unitPrice: number;
  quantity: string;
  totalPrice: string;
}

interface IParticipant {
  _id: string;
  nickname: string;
  avatar: string;
  isSelected: boolean;
}

Page({
  data: {
    orderBillingType: "PAID" as "PAID" | "CHARITY",
    // 模拟的订单数据，实际应从 options 或 API 获取
    orderInfo: {},
    userInfo: {},
    // 复用 outbound 页面的数据结构
    allCategories: [] as ICategory[],
    recyclingList: [] as IOutboundItem[],
    totalAmount: "0.00",
    totalWeight: "0",
    themeColor: "#19be6b",

    // 参与人员列表
    allParticipants: [] as IParticipant[],
    selectedParticipantIds: [] as number[],

    // 备注与状态
    remarks: "",
    isRejectingAction: false, // 是否聚焦于驳回操作，用于高亮备注
    isProcessing: false,
    isRejecting: false,
  },

  onLoad(options: any) {
    const { id } = options;
    this.fetchOrderDetails(id);
    this.addItem(); // 默认添加一个条目
  },
  async fetchOrderDetails(id: string) {
    const data = await orderDetail(id);
    data.allParticipants.forEach((element) => {
      element.isSelected = false;
    });
    const category = await showPrice();
    this.setData({
      allCategories: Object.values(category),
      orderInfo: {
        id: data.order._id,
        orderSnTail: data.order._id.slice(-8),
        school: data.order.address[0].address,
        address: data.order.address[0].formatted_address,
        createTime: new Date(data.order.createdAt).toLocaleString(),
      },
      userInfo: {
        uid: data.order.userId[0]._id,
        avatar: data.order.userId[0].avatar,
        nickname: data.order.userId[0].nickname,
      },
      allParticipants: data.allParticipants,
    });
  },
  // 这里为了完整性，把代码贴出来
  onItemUpdate(e: WechatMiniprogram.CustomEvent) {
    const { index, item } = e.detail;
    this.setData({ [`recyclingList[${index}]`]: item });
    this.calculateGrandTotal();
  },
  async onItemDelete(e: WechatMiniprogram.CustomEvent) {
    const confirm = await showConfirmDialog(
      "确认删除",
      "确定要删除此回收项吗？"
    );
    if (confirm) {
      this.data.recyclingList.splice(e.detail.index, 1);
      this.setData({ recyclingList: this.data.recyclingList });
      this.calculateGrandTotal();
    }
  },
  addItem() {
    const newItem: IOutboundItem = {
      categoryId: null,
      name: "",
      unit: "",
      unitPrice: 0,
      quantity: "",
      totalPrice: "0.00",
    };
    this.data.recyclingList.push(newItem);
    this.setData({ recyclingList: this.data.recyclingList });
  },
  calculateGrandTotal() {
    const total = this.data.recyclingList.reduce(
      (sum, item) => sum + (parseFloat(item.totalPrice) || 0),
      0
    );
    const weight = this.data.recyclingList.reduce(
      (sum, item) => sum + (parseFloat(item.quantity) || 0),
      0
    );
    this.setData({
      totalAmount: total.toFixed(2),
      totalWeight: weight.toFixed(2),
    });
  },
  // --- End of reused methods ---

  // 选择参与人员
  toggleParticipant(e: WechatMiniprogram.TouchEvent) {
    const id = e.currentTarget.dataset.id as string;
    const { allParticipants } = this.data;

    // 找到被点击的参与者，并更新其 isSelected 状态
    const newParticipants = allParticipants.map((p) => {
      if (p._id === id) {
        return { ...p, isSelected: !p.isSelected };
      }
      return p;
    });

    // 根据新的参与者列表，重新计算 selectedParticipantIds
    const newSelectedIds = newParticipants
      .filter((p) => p.isSelected)
      .map((p) => p._id);
    this.setData({
      allParticipants: newParticipants,
      selectedParticipantIds: newSelectedIds,
    });
  },
  onBillingTypeChange(e: WechatMiniprogram.CustomEvent) {
    const newType = e.detail.value as "PAID" | "CHARITY";
    this.setData({
      orderBillingType: newType,
    });
  },
  // 备注处理
  onRemarksInput(e: WechatMiniprogram.CustomEvent) {
    this.setData({ remarks: e.detail.value });
  },
  onRemarkFocus() {
    this.setData({ isRejectingAction: true });
  },
  onRemarkBlur() {
    this.setData({ isRejectingAction: false });
  },

  // 统一校验函数
  validateForm(isReject: boolean = false): boolean {
    // 检查是否至少有一个有效的回收项（已选分类且输入了数量）
    const hasValidItems = this.data.recyclingList.some(
      (item) => item.categoryId && parseFloat(item.quantity) > 0
    );
    if (!hasValidItems && !isReject) {
      showToast("请至少添加一个的回收项");
      return false;
    }

    if (this.data.selectedParticipantIds.length === 0) {
      showToast("请选择参与人员");
      return false;
    }

    if (isReject && !this.data.remarks.trim()) {
      showToast("驳回订单必须填写原因");
      return false;
    }
    return true;
  },

  // 点击驳回按钮
  async onReject() {
    if (!this.validateForm(true)) return;

    this.setData({ isRejecting: true });

    // 准备提交的数据
    const submitData = {
      id: this.data.orderInfo.id,
      reason: this.data.remarks.trim(),
      participantIds: this.data.selectedParticipantIds,
    };
    await backOrder(submitData);
    this.setData({ isRejecting: false });
    showToast("订单已驳回");
    wx.navigateBack();
  },
  contactUser() {
    const { avatar, uid, nickname } = this.data.userInfo;
    router.navigateTo("/pages/im/index", {
      query: {
        peerId: uid,
        peerNickname: nickname,
        peerAvatar: avatar,
        isVirtualPeer: false,
        isCon: true,
      },
    });
  },
  // 点击处理按钮
  async onProcess() {
    if (!this.validateForm(false)) return;

    this.setData({ isProcessing: true });
    const submitData = {
      id: this.data.orderInfo.id,
      billingType: this.data.orderBillingType,
      items: this.data.recyclingList.map((element) => {
        if (element.categoryId && parseFloat(element.quantity) > 0) {
          return {
            orderId: this.data.orderInfo.id,
            weight: Number.parseInt(element.quantity * 1),
            totalPrice: Number.parseInt(element.totalPrice * 100),
            unit: element.unit,
            price: Number.parseInt(element.unitPrice * 100),
            categoryName: element.name,
            categoryId: element.categoryId,
          };
        }
      }),
      totalAmount: Number.parseInt(this.data.totalAmount * 100),
      totalWeight: Number.parseInt(this.data.totalWeight * 1),
      participantIds: this.data.selectedParticipantIds,
      remarks: this.data.remarks.trim(),
    };
    await completeOrder(submitData);
    this.setData({ isProcessing: false });
    showToast("订单处理成功");
    userStore.changePineCoin(Number.parseInt(this.data.totalAmount * 100));
    wx.navigateBack();
  },
});
